
USE Lib
GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
----------------------------

--Enable CLR Integration if is not enabled
IF NOT EXISTS (SELECT * FROM sys.configurations WHERE [name] = 'show advanced options' AND [value] = 1) BEGIN 
	EXEC sp_configure 'show advanced options', 1;
	RECONFIGURE;
	PRINT '<<< Enable SQL Advanced Options - Completed with SUCCESS >>>'
END

IF NOT EXISTS (SELECT * FROM sys.configurations WHERE [name] = 'clr enabled' AND [value] = 1) BEGIN 
	EXEC sp_configure 'clr enabled', 1
	RECONFIGURE
	PRINT '<<< Enable CLR - Completed with SUCCESS >>>'
END

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = 'clr' AND ROUTINE_NAME = 'fn_object_definition' AND ROUTINE_TYPE = 'FUNCTION') BEGIN
	DROP FUNCTION [clr].[fn_object_definition]
	PRINT '<<< DROP FUNCTION [clr].[fn_object_definition] - Completed with SUCCESS >>>'
END


--Drop the assembly if it exist
IF EXISTS (SELECT * FROM sys.assemblies asms WHERE asms.name = N'ClrObjDef') BEGIN 
	DROP ASSEMBLY [ClrObjDef]
	PRINT '<<< DROP Assembly ClrObjDef - Completed with SUCCESS >>>'
END

-- Create the assembly if it does not exists
CREATE ASSEMBLY [ClrObjDef] 
--FROM 'C:\Program Files\Microsoft SQL Server\100\CLR\ClrObjDef.dll' 
-- testing only
FROM 'D:\Projects\SqlLib\Project\CLR\ObjDef\bin\Debug\ClrObjDef.dll' 
WITH PERMISSION_SET = SAFE
	
PRINT '<<< CREATE Assembly ClrRegEx - Completed with SUCCESS >>>'


GO
----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


/*================================================================================================
Name:			[clr].[fn_object_definition]
Type:			Custom CLR UDF
Owner:					
Description:	DDL function, returns the definion of given object  
Parameters:		@object_id  
Dependens on:  	ClrObjDef.dll
Usage:			SELECT clr.fn_object_definition(234423)	
--------------------------------------------------------------------------------------------------
Project:		http://sqllib.codeplex.com/
Help:			http://sqllib.codeplex.com/wikipage?title=fn_object_definition&referringTitle=Documentation		
Version:		20121029
SrcCtrlApp:		SVN
SrcCtrlPath:	http://sqllib.codeplex.com/SourceControl/list/changesets
--------------------------------------------------------------------------------------------------
History:		10/29/2012 - Adrian E Dudau - Function created
================================================================================================*/
--Create the functions
CREATE FUNCTION [clr].[fn_object_definition] 
	( @object_id BIGINT
	 ,@database_id BIGINT
	 )
RETURNS NVARCHAR(MAX)	
AS EXTERNAL NAME ClrObjDef.ClrObjDef.fn_object_definition

GO

